package com.atguigu.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lsyandwh:
 * @create 2022-12-05 20:01
 */
public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {

    private static final Integer BATCH_COUNT = 5;

    //操作数据库对象
    private DictMapper dictMapper;
    //存储解析的数据
    List<ExcelDictDTO> list = new ArrayList<>();

    public ExcelDictDTOListener() {
    }

    public ExcelDictDTOListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(ExcelDictDTO excelDictDTO, AnalysisContext analysisContext) {
        list.add(excelDictDTO);

        if(list.size() >= BATCH_COUNT){
            //执行插入
            insetData();
            //清空集合
            list.clear();
            System.out.println("执行一次插入操作");
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //当数据还有但不超过五条的时候
        if(list.size() > 0){
            dictMapper.insertBatch(list);
        }
        System.out.println("批量添加数据完成");
    }

    private void insetData(){
        dictMapper.insertBatch(list);
    }

}
